package ca.ryerson.rms.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class TabContainerTaglib extends BodyTagSupport
{
	private static final long serialVersionUID = 2759699388053849848L;
	private static String tabs_placeholder = "#tabs";
	
	private static String default_style_filename = "default_style.css";
	
	private String name;
	private String style=default_style_filename;

	public void setName(String name) {
		this.name = name;
	}
	
	public void setStyle(String styleFilename)
	{
		this.style = styleFilename;
	}
	
	public String getStyle() throws IOException
	{
		InputStream inputStyle = getClass().getResourceAsStream("/ca/ryerson/rms/web/" +style);
		
		StringBuilder sb=new StringBuilder();
		BufferedReader br = new BufferedReader(new InputStreamReader(inputStyle));
		String read = br.readLine();
		while(read != null) {
		    sb.append(read + "\n");
		    read =br.readLine();
		}
		
		String style = sb.toString().replace(tabs_placeholder, "#" + name);
		
		return style;
	}

	
	public int doStartTag() throws JspException
	{
		try{
			JspWriter out = pageContext.getOut();
			
			out.write("<style type=\"text/css\">");
			out.newLine();
			
			out.write(getStyle());
			out.newLine();
			
			out.write("</style>");
			out.newLine();
			
			out.write("<div id=\"" + name + "_wrapper\">");
			out.newLine();
			out.write("<div id=\"" + name + "_container\">");
			out.newLine();
			
			//out.write("<ul id=\"" + name + "\">");
		}
		catch(IOException e){  
			throw new JspException(e);
		}
		
		return EVAL_BODY_BUFFERED;
	}
	
	public void doInitBody() throws JspException
	{  
		try{
			bodyContent.write("<ul id=\"" + name + "\">");
			bodyContent.newLine();
		}
		catch(IOException e){  
			e.printStackTrace();  
		}
	}
	
	public int doAfterBody() throws JspException
	{
		try
		{
			bodyContent.write("</ul>");
	    	bodyContent.newLine();
		} 
		catch (IOException e1) {
			e1.printStackTrace();
		}
		
		return SKIP_BODY;
	}
	
	public int doEndTag() throws JspException
	{
		try
		{
			JspWriter out = pageContext.getOut();
			
			BufferedReader br = new BufferedReader(getBodyContent().getReader());
			StringBuilder contents = new StringBuilder();
			try {
				String line = null;
				while (( line = br.readLine()) != null){
					contents.append(line);
					contents.append(System.getProperty("line.separator"));
				}
			}
			finally {
				br.close();
			}
			out.write(contents.toString());

			out.newLine();
			out.write("</div>");
			out.newLine();
			out.write("</div>");
		} 
		catch (IOException e) {
			throw new JspException(e);
		}
		
		return EVAL_PAGE;
    }
}
